package com.hunan.yllxy.util;

import com.alibaba.fastjson2.JSON;
import com.hunan.yllxy.repostitory.entity.UserInfo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author ChenXu
 * @create 2021/3/4 0004a
 */
public class SecurityUtils {

    public static UserInfo getNowUser(){
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userInfo;
    }
    public static boolean checkPassword(String password){
        if(password == null){
            return false;
        }
        password = password.trim();
        if(password.length() < 8){
            return false;
        }
        return Pattern.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[`~!@#$%^&*()\\-+=<>?:\"{}|,.·])[\\da-zA-Z`~!@#$%^&*()\\-+=<>?:\"{}|,.·]{8,}$", password);
    }

    public static void writeJson2Client(HttpServletResponse response, Integer code, Object mess) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        Map<String,Object> datas = new HashMap<>();
        datas.put("code",code);
        datas.put("mess",mess);
        out.write(JSON.toJSONString(datas));
        out.flush();
        out.close();
    }
}
